package com.share.module.business.stock.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.module.business.stock.dao.StockDAO;
import com.share.module.business.stock.entity.Stock;
import com.share.module.business.stock.vo.StockPageQueryVO;
import com.share.module.business.stock.vo.StockPageVO;
import com.stock.common.collect.ListUtils;
import com.stock.common.lang.StringUtils;
import com.stock.mybatisplus.utils.PageUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 股票表 服务实现类
 * </p>
 *
 * @author system
 * @since 2025-11-02
 */
@Service
public class StockService extends ServiceImpl<StockDAO, Stock> {

    /**
     * 分页查询股票列表
     */
    public PageUtils<StockPageVO> page(StockPageQueryVO vo) {
        LambdaQueryWrapper<Stock> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StringUtils.isNotBlank(vo.getName()), Stock::getName, vo.getName());
        wrapper.like(StringUtils.isNotBlank(vo.getCode()), Stock::getCode, vo.getCode());
        wrapper.orderByDesc(Stock::getId);
        IPage<Stock> page = super.page(new Page<>(vo.getCurrPage(), vo.getSize()), wrapper);

        List<StockPageVO> targets = page.getRecords().stream().map(item -> {
            StockPageVO pageVO = new StockPageVO();
            pageVO.setId(item.getId());
            pageVO.setName(item.getName());
            pageVO.setCode(item.getCode());
            pageVO.setUrl(item.getUrl());
            return pageVO;
        }).collect(Collectors.toList());

        return new PageUtils<>(targets, page.getTotal(), page.getSize(), page.getCurrent());
    }

    public Stock getFirst(String stockCode, String stockName) {
        LambdaQueryWrapper<Stock> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StringUtils.isNotBlank(stockName), Stock::getName, stockName);
        wrapper.like(StringUtils.isNotBlank(stockCode), Stock::getCode, stockCode);
        wrapper.orderByDesc(Stock::getId);
        List<Stock> list = this.list(wrapper);
        return ListUtils.getFirst(list);
    }
}
